package com.js.nickcar.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.js.nickcar.R;
import com.js.nickcar.entity.local.City;
import com.js.nickcar.entity.local.Province;
import com.js.nickcar.widget.wheel.WheelView;
import com.js.nickcar.widget.wheel.adapter.ArrayWheelAdapter;
import com.js.nickcar.widget.wheel.intef.OnWheelScrollListener;
import com.zyzd.commontools.json.GsonUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;


/**
 * Created by LZY on 2017/6/20.
 */

public class RegionDialog extends Dialog implements View.OnClickListener {
    public ArrayList<Province> provinces;
    public String[] pros;
    public String[] curCitiesArr;
    private WheelView province;
    private WheelView city;
    private String[] initValue;
    private ArrayList<City> curCities;
    private OnRegionListener onRegionListener;
    /**
     * 滚动结束的监听
     */
    private OnWheelScrollListener scrollListener = new OnWheelScrollListener() {

        @Override
        public void onScrollingStarted(WheelView wheel) {

        }

        @Override
        public void onScrollingFinished(WheelView wheel) {
            if (wheel == province) initCity();
        }
    };


    public RegionDialog(Context context, String[] initValue) {
        this(context, R.style.dialog_wheel, initValue);
        // 让Dialog显示在底部
        getWindow().setGravity(Gravity.BOTTOM);
    }

    public RegionDialog(Context context, int themeResId, String[] initValue) {
        super(context, themeResId);
        this.initValue = initValue;
        View contentView = getLayoutInflater().inflate(R.layout.dialog_region_wheel, null);
        province = (WheelView) contentView.findViewById(R.id.province);
        city = (WheelView) contentView.findViewById(R.id.city);

        provinces = GsonUtil.fromJson(getAreaInfo(context), new TypeToken<ArrayList<Province>>() {
        }.getType());

        initProvince();
        province.setCurrentItem(getInitIndex(0, getProvince()));

        initCity();
        city.setCurrentItem(getInitIndex(1, curCitiesArr));


        province.setVisibleItems(5);
        city.setVisibleItems(5);

        province.addScrollingListener(scrollListener);
        city.addScrollingListener(scrollListener);

        // 设置监听
        TextView ok = (TextView) contentView.findViewById(R.id.tv_confirm);
        TextView cancel = (TextView) contentView.findViewById(R.id.tv_cancel);
        ok.setOnClickListener(this);
        cancel.setOnClickListener(this);

        // 去掉标题，必须在setContentView之前调用
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(contentView);
        // 设置Dialog的宽度等于屏幕的宽度，必须在setContentView后调用
        WindowManager.LayoutParams p = getWindow().getAttributes();
        p.width = WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setAttributes(p);
        getWindow().setWindowAnimations(R.style.AnimBottom);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        );
    }



    private void initCity() {
        getCity();
        ArrayWheelAdapter cityAdapter = new ArrayWheelAdapter(getContext(), curCitiesArr);
        this.city.setViewAdapter(cityAdapter);
        this.city.setCyclic(false);
        if (curCitiesArr.length > 0) {
            this.city.setCurrentItem(0);
        }
    }

    /**
     * 获取城市名
     *
     * @return
     */
    private void getCity() {
        curCities = provinces.get(province.getCurrentItem()).getCity();

        if (curCities == null) {
            curCities = new ArrayList<>();
        }

        if (curCities.size() == 0) {
            City city = new City();
            city.setName("请选择");
            curCities.add(city);
        }

        curCitiesArr = new String[curCities.size()];
        for (int i = 0; i < curCities.size(); i++) {
            curCitiesArr[i] = curCities.get(i).getName();
        }

    }

    /**
     * 获取已有的区域地址初始值对应的角标
     *
     * @param i
     * @param array
     * @return
     */
    private int getInitIndex(int i, String[] array) {
        if (initValue == null || initValue.length < (i + 1) || initValue[i] == null) {
            return 0;
        }
        for (int index = 0; index < array.length; index++) {
            if (array[index].equals(initValue[i])) {
                return index;
            }
        }
        return 0;
    }

    /**
     * 获取省名
     *
     * @return
     */
    private String[] getProvince() {
        if (pros != null && pros.length > 1) {
            return pros;
        }

        if (provinces == null)
            return new String[]{"请选择"};

        pros = new String[provinces.size()];
        for (int i = 0; i < provinces.size(); i++) {
            pros[i] = provinces.get(i).getName();
        }
        return pros;
    }

    private void initProvince() {
        ArrayWheelAdapter<String> provinceAdapter = new ArrayWheelAdapter(getContext(), getProvince());
        //numericWheelAdapter.setTextSize(15);  设置字体大小
        province.setViewAdapter(provinceAdapter);
        province.setCyclic(true);
    }

    /**
     * 从资产目录下获取地区json数据
     *
     * @param context
     * @return
     */
    @NonNull
    private String getAreaInfo(Context context) {
        AssetManager assetsManager = context.getAssets();
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        try {
            inputStream = assetsManager.open("region/china.json");
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String lineText = null;
            while ((lineText = bufferedReader.readLine()) != null) {
                sb.append(lineText);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (bufferedReader != null) {
                    bufferedReader.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_confirm:
                positiveSet(v);
                break;
            case R.id.tv_cancel:
                cancelSet(v);
                break;
        }
    }

    /**
     * 取消
     *
     * @param v
     */
    private void cancelSet(View v) {
        cancel();
    }

    /**
     * 确定
     *
     * @param v
     */
    private void positiveSet(View v) {
        if (onRegionListener != null) {
            Province province = provinces.get(this.province.getCurrentItem());
            City city = province.getCity().get(this.city.getCurrentItem());
            onRegionListener.onPositive(v, province, city);
        }
        cancel();
    }

    public void setOnRegionListener(OnRegionListener onRegionListener) {
        this.onRegionListener = onRegionListener;
    }

    public interface OnRegionListener {
        void onPositive(View view, Province province, City city);
    }
}
